<template>
  <view viewport>
    <view class="card">
      <view class="row_container">
        <view class="row_container_title">品牌:</view>
        <view class="row_container_content">
          <input class="uni-input" placeholder="请输入品牌" placeholder-style="color:#C3C6CD" v-model="form.brand" />
        </view>
      </view>
      <view class="line"></view>
      <view class="row_container">
        <view class="row_container_title">型号:</view>
        <view class="row_container_content">
          <input class="uni-input" placeholder="请输入型号" placeholder-style="color:#C3C6CD" v-model="form.model" />
        </view>
      </view>
      <view class="line"></view>
      <view class="row_container">
        <view class="row_container_title">竞品分类:</view>
        <view class="row_container_content" @click="open">
          <input class="uni-input" placeholder="请选择竞品分类" placeholder-style="color:#C3C6CD" v-model="form.classifyName"
            disabled>
        </view>
      </view>
      <view class="line"></view>
      <view class="row_container">
        <view class="row_container_title">对标型号:</view>
        <view class="row_container_content">
          <input class="uni-input" placeholder="请输入对标型号" placeholder-style="color:#C3C6CD"
            v-model="form.benchmarkingModel" />
        </view>
      </view>
      <view class="line"></view>
      <view class="row_container">
        <view class="row_container_title">价格:</view>
        <view class="row_container_content">
          <input class="uni-input" placeholder="请输入价格" placeholder-style="color:#C3C6CD" type='digit'
            v-model="form.price" />
        </view>
      </view>
      <view class="line"></view>
      <view class="row_container">
        <view class="row_container_title">热度:</view>
        <view class="row_container_content">
          <uni-data-select :clear="false" :localdata="array" placeholder-style="color:#C3C6CD" placeholder="请选择热度"
            :styles="styles" v-model="form.popular"></uni-data-select>
        </view>
      </view>
      <view class="line"></view>
      <view class="row_container">
        <view class="row_container_title">销售区域:</view>
        <view class="row_container" @click="getLocation">
          <input class="input" v-model="location" placeholder="请选择位置" />
          <image class="add" src="../../static/images/icon_location.png"></image>
        </view>
      </view>
      <view class="line"></view>
      <view class="column_container">
        <view class="row_container_title">备注:</view>
        <view class="column_container_content">
          <textarea class="text_area" v-model="form.memo" placeholder-style="color:#C3C6CD;font-size:30rpx"
            placeholder="请输入备注"></textarea>
        </view>
      </view>
      <view class="line"></view>
      <view class="row_container">

        <view class="row_container_title">照片:</view>
      </view>
      <view v-if="fileList.length>0" class="container_upload_img">
        <view class="item_upload_view" v-for="(imageItem, index) in fileList" :key="index">
          <image :mode="imageItem.isAdd?'aspectFit':'aspectFill'" class="item_upload_img"
            :src="imageItem.isAdd?'../../static/images/icon_camera_square.png':imageItem.url"
            @click="tagClick(imageItem,fileList)">
          </image>
          <image class="item_delete" v-if="!imageItem.isAdd" src="../../static/images/icon_delete_line.png"
            @click.stop="deleteItem(fileList,index)">
          </image>
        </view>
      </view>

    </view>

    <view class="bottom-contianer">
      <button class="button_normal" @click="cancel">取消</button>
      <button class="button" @click="commit">提报</button>
    </view>
  </view>
  <wCascader v-model="form.classifyName" title="产品分类" @finish="finish" :list="productList" ref="cascaRef"
    labelKey="classtreeName" valueKey="classtreeCode" childrenKey="childList"
    :tabProps="{ lineColor: '#54B9CC', activeColor: '#333', bgColor: '#fff' }" />
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import Func from '@/utils/func'
  import { queryClCompetitorPage, saveClCompetitor } from '@/services/competition'
  import { reginDetail } from '@/utils/location'
  import type { fileItem } from '@/types/files'
  import { uploadFilePromise } from '@/utils/upload'
  import wCascader from '@/components/w-cascader/w-cascader.vue'
  import { getClasstree } from '@/services/file'

  const form = ref({
    brand: '',
    model: '',
    benchmarkingModel: '',
    classifyName: '',
    firstClassify: '',
    secondClassify: '',
    thirdClassify: '',
    price: '',
    popular: 1,
    areaCode: '',
    areaFullName: '',
    memo: '',
    attachIds: ''
  })

  const array = ref([{ text: '高', value: 1 }, { text: '中', value: 2 }, { text: '低', value: 3 }])

  const styles = "{ color: '#333',backgroundColor: rgba(179, 220, 246, 0.10),disableColor: '#F7F6F6',borderColor: '#e5e5e5'}"
  const selectedValue = ref() // 存储选中的value
  const selectedText = ref('高')   // 存储显示的key（用于界面展示）默认为高

  //所在位置
  const location = ref('')
  //产品库李彪
  const productList = ref<any[]>([])
  //选择产品级联选择器
  const cascaRef = ref(null)
  //附件列表
  const fileList = ref<any[]>([{
    url: '',
    id: '',
    isAdd: true
  }])

  onLoad(() => {
    getClasstree({ goodsClass: 'B2B' }).then((res : any) => {
      const firstClasstree = res;
      if (Func.notEmpty(firstClasstree)) {
        productList.value = firstClasstree
      }

    })
  })
  //打开选择器
  const open = () => {
    console.log('open')
    cascaRef.value.open()
  }

  //选择地址
  const getLocation = () => {
    console.log('selectCity')
    uni.chooseLocation({
      success: function (res) {
        console.log('selectCity', res)
        location.value = res.address
        reginDetail(res.longitude, res.latitude).then(res => {
          console.log(res)
          location.value = res?.province + res?.city + res?.district
          form.value.areaCode = res?.district
          form.value.areaFullName = location.value
        })
      },
    })
  }
  //删除
  const deleteItem = (imagesList : any, index : number) => {
    imagesList.splice(index, 1);
  }
  //列表展示
  const tagClick = (item : any, images : any) => {
    console.log(item)
    if (item.isAdd) {
      uni.chooseImage({
        count: 1,
        secret: false,
        position: 'back',
        sourceType: ['camera', 'album'],
        success: (res : any) => {
          console.log('选择的文件列表:', res.tempFiles[0].path);
          // res.tempFiles 结构： [{ path: '临时路径', name: '文件名', size: 文件大小, type: '文件类型' }]
          uploadFilePromise(res.tempFiles[0].path).then((result : any) => {
            console.log(result)
            images.splice(0, 0, {
              url: result.url,
              id: result.fileId,
              isAdd: false
            })
          })


        },
        fail: () => { },
        complete: () => { },
      });
    } else {
      var urls = []
      urls.push(item.url)
      uni.previewImage({
        urls: urls,
        current: 0,
        success: () => { },
        fail: () => { },
        complete: () => { },
      });
    }
  }
  //删除文件
  const removeFile = (index : number) => {
    fileList.value.splice(index, 1)
  }

  const cancel = () => {
    uni.navigateTo({
      url: '/pagesMember/competition/index'
    })
  }
  //选择商品回调
  const finish = (e : any) => {
    console.log(e)
    form.value.classifyName = e.label
    const values = e.value.split('/')
    form.value.firstClassify = values[0] || ''
    form.value.secondClassify = values[0] || ''
    form.value.thirdClassify = values[0] || ''
  }
  //提交
  const commit = () => {
    const params = form.value;
    // 校验必填参数
    if (Func.isEmpty(params.brand)) {
      uni.showToast({
        title: '请输入品牌',
        icon: 'none',
      })
      return
    }
    if (Func.isEmpty(params.model)) {
      uni.showToast({
        title: '请输入型号',
        icon: 'none',
      })
      return
    }
    if (Func.isEmpty(params.benchmarkingModel)) {
      uni.showToast({
        title: '请输入对标型号',
        icon: 'none',
      })
      return
    }
    if (Func.isEmpty(params.classifyName)) {
      uni.showToast({
        title: '请选择竞品分类',
        icon: 'none',
      })
      return
    }
    if (Func.isEmpty(params.price)) {
      uni.showToast({
        title: '请输入价格',
        icon: 'none',
      })
      return
    }
    if (Func.isEmpty(params.popular)) {
      uni.showToast({
        title: '请选择热度',
        icon: 'none',
      })
      return
    }
    if (Func.isEmpty(params.areaFullName)) {
      uni.showToast({
        title: '请选择销售区域',
        icon: 'none',
      })
      return
    }
    console.log(fileList.value.length)
    if (fileList.value.length <= 1) {
      uni.showToast({
        title: '请先上传附件',
        icon: 'none',
      })
      return
    }
    //去掉 添加 项目
    const newUrlList = fileList.value.splice(0, fileList.value.length - 1)
    console.log(newUrlList)
    // 附件id用逗号分隔保存
    const attachIds = newUrlList.map(item => item.url).join(',');

    params.attachIds = attachIds;

    console.log(form.value)
    saveClCompetitor(params).then(res => {
      console.log(res)
      if (res.success) {
        uni.navigateBack()
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        })
      }
    })
  }
</script>

<style lang="scss" scoped>
  /* 穿透 scoped 样式修改选中项 */
  ::v-deep .uni-data-select-item--selected {
    background-color: #ff0000 !important;
    /* 红色背景 */
    color: #ffffff !important;
    /* 白色文字 */
    border-radius: 8px !important;
    /* 圆角 */
  }

  /* 修改下拉框整体样式 */
  ::v-deep .uni-data-select {
    --dropdown-background: #f8f8f8;
    /* 自定义 CSS 变量（如果组件支持） */
  }

  /* 仅在当前页面生效 */
  page {
    background-color: #F9FAFB;
  }

  .viewport {
    display: flex;
  }

  .card {
    margin: 20rpx 20rpx;
    background: #FFFFFF;
    display: flex;
    padding: 24rpx;
    padding-bottom: 150rpx;
    flex-direction: column;
    // box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(209, 227, 230, 0.58);
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }

  .column_container {
    margin-top: 24rpx;
    margin-bottom: 24rpx;
    margin-left: 5rpx;
    display: flex;
    flex-direction: column;
  }

  .column_container_content {
    margin-top: 20rpx;
    padding-left: 25rpx;
  }

  .text_area {
    height: 120rpx
  }

  .row_container {
    margin-top: 24rpx;
    margin-bottom: 24rpx;
    margin-left: 5rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
  }


  .row_container_title {
    min-width: 140rpx;
    font-size: 32rpx;
    color: #1C253A
  }

  .add {
    width: 55rpx;
    height: 55rpx;
    margin-left: 120rpx;
  }

  .row_container_content {
    padding: 5rpx 0rpx;
    font-size: 30rpx;
    margin-left: 25rpx;
    color: #394259;
    flex-grow: 1;
  }

  .line {
    background-color: #F2F3F5;
    height: 1rpx;
  }



  .bottom-contianer {
    position: fixed;
    bottom: 40rpx;
    width: 100%;
    display: flex;
    flex-direction: row;
  }

  .button {
    width: 45%;
    background-color: #54B9CC;
    color: white;
    font-size: 32rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }

  .button_normal {
    width: 45%;
    color: #54B9CC;
    font-size: 32rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 2rpx solid #54B9CC;
  }

  .picker {
    padding: 20px;
    background-color: #f5f5f5;
    margin: 20px;
    text-align: center;
  }

  .input {
    flex-grow: 1;
    color: #C3C6CD;
    font-size: 30rpx;
    margin-left: 25rpx;
  }

  .line_vertical {
    width: 8rpx;
    height: 30rpx;
    margin-right: 10rpx;
    background: linear-gradient(180deg, #61D7ED 0%, #54B9CC 100%);
    border-radius: 4rpx 4rpx 4rpx 4rpx;
  }

  .add_text {
    margin-left: 10rpx;
    height: 44rpx;
    font-size: 30rpx;
    color: #54B9CC;
    line-height: 44rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .add_text_plus {
    margin-left: 15rpx;
    height: 44rpx;
    font-size: 44rpx;
    color: #54B9CC;
    line-height: 44rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .row_container_end {
    margin-right: 5rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    flex-grow: 1;
  }

  .common_title {
    height: 48rpx;
    line-height: 48rpx;
    font-size: 32rpx;
    color: #1C253A;
    font-weight: bold;
  }

  .container_upload_img {
    width: 93vw;
    display: flex;
    margin-left: 20rpx;
    row-gap: 15rpx;
    column-gap: 12rpx;
    flex-wrap: wrap;


  }

  .item_upload_view {
    position: relative;
    display: flex;
    margin: 10rpx 5rpx;
    align-items: flex-end;
  }

  .item_delete {
    position: absolute;
    right: 0rpx;
    top: 0rpx;
    z-index: 1;
    width: 44rpx;
    height: 44rpx;
  }

  .item_upload_img {
    margin-top: 20rpx;
    width: 40vw;
    margin-right: 20rpx;
    height: 176rpx;
    font-size: 30rpx;
    color: #1685fb;
    text-decoration: underline
  }
</style>
